<template>
  <div class="reset-password-container">
    <el-card class="reset-password-card">
      <template #header>
        <div class="card-header">
          <span>重置密码</span>
        </div>
      </template>
      
      <el-form ref="resetPasswordForm" :model="passwordForm" label-width="100px" class="reset-password-form">
        <el-form-item label="原密码" prop="oldPwd" :rules="[
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ]">
          <el-input v-model="passwordForm.oldPwd" type="password" placeholder="请输入原密码" show-password />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPwd" :rules="[
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' },
          { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
        ]">
          <el-input v-model="passwordForm.newPwd" type="password" placeholder="请输入新密码（6-20位字母数字组合）" show-password />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="rePwd" :rules="[
          { required: true, message: '请确认新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== passwordForm.newPwd) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]">
          <el-input v-model="passwordForm.rePwd" type="password" placeholder="请再次输入新密码" show-password />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">提交修改</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus'
import request from '../utils/request.js'
import useUserStore from '../store/user.js'

// 获取用户 store
const userStore = useUserStore()

// 表单引用
const resetPasswordForm = ref(null)

// 密码表单数据
const passwordForm = ref({
  oldPwd: '',
  newPwd: '',
  rePwd: ''
})

// 加载状态
const loading = ref(false)

// 提交修改
const handleSubmit = async () => {
  try {
    // 验证表单
    await resetPasswordForm.value.validate()
    
    // 设置加载状态
    loading.value = true
    
    // 调用重置密码接口
    const response = await request.patch('/user/updatePwd', passwordForm.value)
    
    if (response.code === 0) {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除用户信息并重定向到登录页面
      setTimeout(() => {
        userStore.logout()
      }, 1500)
    } else {
      ElMessage.error(response.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码错误:', error)
    if (error.message && !error.message.includes('Error: Request failed')) {
      // 表单验证失败的错误不需要显示
    } else {
      ElMessage.error('网络错误，请重试')
    }
  } finally {
    // 重置加载状态
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 重置表单
  resetPasswordForm.value.resetFields()
}
</script>

<style scoped>
.reset-password-container {
  height: 100%;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.reset-password-card {
  width: 500px;
  max-width: 90%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reset-password-form {
  margin-top: 20px;
}
</style>